<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
      <el-form-item label="收件人姓名" prop="recipients" :class="{ 'is-required': true }">
        <el-input v-model="dataForm.recipients" placeholder="收件人姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile" :class="{ 'is-required': true }">
        <el-input v-model="dataForm.mobile" placeholder="手机号码"></el-input>
      </el-form-item>
      <el-form-item label="省市区县" prop="addr" :class="{ 'is-required': true }">
        <!-- <el-input v-model="dataForm.addr" type="hidden" placeholder="省市区县"></el-input> -->
        <div class="linkage">
          <el-select
            v-model="sheng"
            @change="choseProvince"
            style="width:120px"
            placeholder="省级地区">
            <el-option
              v-for="item in province"
              :key="item.id"
              :label="item.value"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select
            v-model="shi"
            @change="choseCity"
            style="width:120px"
            placeholder="市级地区">
            <el-option
              v-for="item in shi1"
              :key="item.id"
              :label="item.value"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select
            v-model="qu"
            @change="choseBlock"
            style="width:120px"
            placeholder="区级地区">
            <el-option
              v-for="item in qu1"
              :key="item.id"
              :label="item.value"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="详细地址" prop="detail" :class="{ 'is-required': true }">
        <el-input v-model="dataForm.detail" placeholder="详细地址"></el-input>
      </el-form-item>
      <el-form-item label="用户Id" prop="userId" :class="{ 'is-required': true }">
        <el-input v-model="dataForm.userId" placeholder="用户Id"></el-input>
      </el-form-item>
      <el-form-item label="标签" size="mini" prop="flagList">
        <el-checkbox-group v-model="dataForm.flagList">
          <el-checkbox v-for="x in flagList" :key="x.val" :label="x.val">{{ x.txt }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="是否默认" size="mini" prop="def">
        <el-radio-group v-model="dataForm.def">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { isMobile } from '@/utils/validate'
  import axios from 'axios'
  export default {
    data () {
      var validateRecipients = (rule, value, callback) => {
        if (!/\S/.test(value)) {
          callback(new Error('收件人姓名不能为空哦'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号码格式错误'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        flagList: [],
        dataForm: {
          id: 0,
          recipients: '',
          mobile: '',
          addr: '',
          detail: '',
          flagList: [],
          def: 0,
          userId: ''
        },
        dataRule: {
          recipients: [
            { required: true, message: '收件人姓名不能为空', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
            { validator: validateRecipients, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '手机号码不能为空', trigger: 'blur' },
            { validator: validateMobile, trigger: 'blur' }
          ],
          addr: [
            { required: true, message: '请选择省市县区', trigger: 'blur' }
          ],
          detail: [
            { required: true, message: '请输入详细地址信息', trigger: 'blur' }
          ],
          userId: [
            { required: true, message: '用户ID不能为空', trigger: 'blur' }
          ]
        },
        mapJson: '../static/json/map.json',
        province: [],
        city: [],
        block: [],
        sheng: '',
        shi: '',
        qu: '',
        shi1: [],
        qu1: []
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/addr/flags'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.flagList = data && data.code === 0 ? data.list : []
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/addr/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.recipients = data.addr.recipients
                this.dataForm.userId = data.addr.userId
                this.dataForm.addr = data.addr.addr
                this.dataForm.mobile = data.addr.mobile
                this.dataForm.detail = data.addr.detail
                console.info(data.addr.flagList)
                this.dataForm.flagList = data.addr.flagList || []
                this.dataForm.def = data.addr.def
                // 处理省市县级联
                this.sheng = data.addr.addr.slice(0, 2) + '0000'
                // 此处需要触发选择省份事件，用于加载市、区数据，从而才能正常显示市、区
                this.choseProvince(this.sheng)
                this.shi = data.addr.addr.slice(0, 4) + '00'
                this.choseCity(this.shi)
                this.qu = data.addr.addr
                this.choseBlock(this.qu)
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          console.info('valid = ' + valid)
          if (valid) {
            // 处理地址
            this.dataForm.addr = this.E
            this.$http({
              url: this.$http.adornUrl(`/sys/addr/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'recipients': this.dataForm.recipients,
                'mobile': this.dataForm.mobile,
                'addr': this.dataForm.addr,
                'userId': this.dataForm.userId,
                'detail': this.dataForm.detail,
                'flagList': this.dataForm.flagList,
                'def': this.dataForm.def
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 加载china地点数据，三级
      getCityData () {
        var that = this
        axios.get(this.mapJson).then((response) => {
          if (response.status === 200) {
            var data = response.data
            that.province = []
            that.city = []
            that.block = []
            // 省市区数据分类
            for (var item in data) {
              if (item.match(/0000$/)) {
                // 省
                that.province.push({id: item, value: data[item], children: []})
              } else if (item.match(/00$/)) {
                // 市
                that.city.push({id: item, value: data[item], children: []})
              } else {
                // 区
                that.block.push({id: item, value: data[item]})
              }
            }
            // 分类市级
            for (var index in that.province) {
              for (var index1 in that.city) {
                if (that.province[index].id.slice(0, 2) === that.city[index1].id.slice(0, 2)) {
                  that.province[index].children.push(that.city[index1])
                }
              }
            }
            // 分类区级
            for (var item1 in that.city) {
              for (var item2 in that.block) {
                if (that.block[item2].id.slice(0, 4) === that.city[item1].id.slice(0, 4)) {
                  that.city[item1].children.push(that.block[item2])
                }
              }
            }
          } else {
            console.log(response.status)
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 选省
      choseProvince (e) {
        for (var index2 in this.province) {
          if (e === this.province[index2].id) {
            this.shi1 = this.province[index2].children
            this.shi = this.province[index2].children[0].value
            this.qu1 = this.province[index2].children[0].children
            this.qu = this.province[index2].children[0].children[0].value
            this.E = this.qu1[0].id
          }
        }
      },
      // 选市
      choseCity (e) {
        for (var index3 in this.city) {
          if (e === this.city[index3].id) {
            this.qu1 = this.city[index3].children
            this.qu = this.city[index3].children[0].value
            this.E = this.qu1[0].id
            // console.log(this.E)
          }
        }
      },
      // 选区
      choseBlock (e) {
        this.E = e
        this.qu = e
        console.log(this.E)
      }
    },
    created () {
      this.getCityData()
    }
  }
</script>
